from loguru import logger
import requests
from service.utils import config
import json
from more_itertools import chunked
import time


# 获取 SteamDT 数据（api，参考：https://doc.steamdt.com/）
def request_steamdt_by_api(
    options=[],
    api_key=config.get("STEAMDT", "APIKEY"),
):
    result = []
    options = list(chunked(options, 100))
    url = "https://open.steamdt.com/open/cs2/v1/price/batch"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}",
        "Accept": "*/*",
        "Host": "open.steamdt.com",
        "Connection": "keep-alive",
    }
    for option in options:
        try:
            payload = json.dumps(
                {"marketHashNames": list(map(lambda x: x["item_name"], option))},
                ensure_ascii=False,
            )
            response = requests.post(
                url, headers=headers, data=payload, timeout=10
            ).json()
            if (
                response.get("success", False) is False
                or len(response.get("data", [])) == 0
            ):
                raise Exception("空数据或请求失败！")
            else:
                result.extend(response.get("data", []))
        except Exception as e:
            logger.error(f"steamdt请求失败: {e}")
            if response is not None:
                logger.error(json.dumps(response))
        finally:
            if len(options) > 1:
                time.sleep(62)
    return result
